package cn.whb.hrm.exceptionhandle;

import cn.whb.hrm.constant.GlobalStatusCode;
import cn.whb.hrm.util.AjaxResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice //在所有controller声明切面
public class GlobalException {

//    @ExceptionHandler(value = RuntimeException.class)
//    public AjaxResult handleException(RuntimeException e){
//        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(GlobalStatusCode.GLOBAL_EXCEPTION_ERROR.getCode());
//    }

    /**
     * 处理js303的异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult handleException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();
        Map<String, Object> map = new HashMap<>();
        errors.stream().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        return AjaxResult.me().setSuccess(false).setMessage(map.toString()).setCode(HttpStatus.BAD_REQUEST.value());
    }
}
